<template>
    <div class="grandpa">
        爷爷，家庭总资产为{{ assets }}元
        <el-button style="margin-left: 2rem" @click="makeMoney(10)">赚钱</el-button>
        <el-button @click="spendMoney(10)">花钱</el-button>
        <Father />
    </div>
</template>

<script lang="ts">
import { defineComponent, provide, ref } from 'vue';
import Father from './Father.vue';

export default defineComponent({
    name: 'Grandpa',
    components: {
        Father
    },
    setup() {
        const assets = ref(0);

        // 赚钱
        const makeMoney = (money: number) => {
            assets.value += money;
            console.log(`爷爷赚了${money}元，总资产变为${assets.value}元`);
        };

        // 花钱
        const spendMoney = (money: number) => {
            if (assets.value >= money) {
                assets.value -= money;
                console.log(`爷爷花了${money}元，总资产变为${assets.value}元`);
            } else {
                console.error('家庭总资产不足');
            }
        };

        // 提供总资产和更新方法
        provide('assets', assets);
        provide('updateAssets', (newAssets: number) => {
            assets.value = newAssets;
            console.log(`总资产更新为${newAssets}元`);
        });

        return {
            assets,
            makeMoney,
            spendMoney
        };
    }
});

</script>

<style lang='scss' scoped>
.grandpa {
    width: 50vw;
    height: 40rem;
    margin: 0 auto;
    border: 1px solid #000;
    border-radius: 5px;
    padding: 2rem;
    margin-top: 2rem;
}
</style>